package cn.toolck.service.impl;

import cn.toolck.pojo.LagouToken;
import cn.toolck.pojo.LagouUserInfo;
import cn.toolck.service.LagouAuthCodeService;
import cn.toolck.user.service.LagouTokenService;
import cn.toolck.user.service.LagouUserInfoService;
import cn.toolck.user.service.UserService;
import cn.toolck.util.CookieUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Reference
    private LagouAuthCodeService lagouAuthCodeService;
    @Autowired
    private LagouTokenService lagouTokenService;
    @Autowired
    private LagouUserInfoService lagouUserInfoService;

    /**
     * 注册接⼝
     *
     * @param email    邮箱
     * @param password 密码
     * @param code     验证码
     * @return true成功，false失败
     */
    public int register(String email, String password, String code) {
        int validate = lagouAuthCodeService.validate(email, code);
        if (validate == 0 && !isRegistered(email)) {
            lagouUserInfoService.insert(email, password);
        }
        return validate;
    }

    /**
     * 是否已注册
     *
     * @param email 邮箱
     * @return true代表已经注册过，false代表尚未注册
     */
    public boolean isRegistered(String email) {
        return lagouUserInfoService.findOneByEmail(email).isPresent();
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @param email 邮箱
     * @return 邮箱地址
     */
    public boolean login(String email, String password, HttpServletResponse response) {
        Optional<LagouUserInfo> lagouUserInfoOptional = lagouUserInfoService.findOneByEmail(email);
        boolean result = lagouUserInfoOptional.isPresent()
                && Objects.equals(lagouUserInfoOptional.get().getPassword(), password);
        if (result) {
            String token = UUID.randomUUID().toString();
            CookieUtil.createCookie("token", token, "/", response);
            lagouTokenService.insertOrUpdate(email, token);
        }
        return result;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token token
     * @return 邮箱
     */
    public String info(String token) {
        Optional<LagouToken> lagouTokenOptional = lagouTokenService.findOneByToken(token);
        return lagouTokenOptional.orElse(new LagouToken()).getEmail();
    }
}
